﻿using System;
using System.Collections.Generic;
using System.Xml.Linq;
using SharePhone.Common.Web;
using SharePhone.Core;
using SharePhone.Provider;
using SharePhone.Query;

namespace SharePhone.Common.List
{
    public delegate void ItemsLoadCompleteHandler(object sender, EventArgs e);

    public class SPList<T> : FrameworkObject where T : BaseItem, new()
    {
        private BaseItemList<T> ItemCache { get; set; }
        public SPWeb ParentWeb { get; set; }
        public string Title { get; set; }

        public BaseItemList<T> Items
        {
            get
            {
                if (ItemCache == null || ItemCache.CacheStatus == CacheStatus.Old)
                {
                    ItemCache = new BaseItemList<T>();
                    ItemCache.ParentList = this;
                }
                return ItemCache;
            }
        }


        public int ItemCount { get; set; }
        public string Modified { get; set; }
        public string Created { get; set; }
        public string Name { get; set; }
        public int BaseType { get; set; }

        public bool RequireCheckout { get; set; }
        public bool EnableAttachments { get; set; }
        public bool EnableMinorVersion { get; set; }
        public bool EnableVersioning { get; set; }
        public bool EnableModeration { get; set; }

        public RegionalSettings RegionalSettings { get; set; }
        public List<FieldInfo> Fields { get; internal set; }

        public void GetItemsByQuery(CamlExpression query, int rowLimit, ListItemsTransferCompleted<T> itemsHandler)
        {
            GetItemsByQuery(CamlQuery.BuildQuery(query, null, CamlQuery.Scope.Recursive, null), rowLimit, itemsHandler);
        }

        public void GetItemsByQuery(string query, int rowLimit, ListItemsTransferCompleted<T> itemsHandler)
        {
            XDocument doc = XDocument.Parse(query);
            XElement q = doc.Element("Where");
            ListItemProvider.GetListItems(ParentWeb, this, rowLimit, itemsHandler, q, ParentWeb.Settings.Credentials);
        }

        public void Update()
        {
            ListProvider.UpdateList(this, ParentWeb.Url, ParentWeb.Settings.Credentials);
        }

        public override string ToString()
        {
            return Title;
        }
    }
}